﻿namespace gRPCDemo.OpcPublish
{
    public class Client
    {
        //调OPC发布程序的Grpc接口
        public async Task OpcPublishGrpcTest()
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);
            var channel = GrpcChannel.ForAddress("http://localhost:19007");
            var publisherClient = new OpcPublisher.OpcPublisherClient(channel);
            var request = new DataRequest();
            var list = new[] {
                new KeyData{  Key="ZS/ZS_1/Result/Position",        Value="111.111", Type="Double", Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
                new KeyData{  Key="ZS/ZS_1/Result/Length",          Value="222.222", Type="Double", Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
                new KeyData{  Key="ZS/ZS_1/Result/AlarmCount",      Value="333",    Type="Int32",  Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
                new KeyData{  Key="ZS/ZS_1/Result/AlarmLevel",      Value="3",       Type="Int16",  Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
                new KeyData{  Key="ZS/ZS_1/Status/MainBeltFault",   Value="true",    Type="Bool",   Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
                new KeyData{  Key="ZS/ZS_1/Status/PowerBoardFault", Value="false",   Type="Bool",   Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
                new KeyData{  Key="ZS/ZS_1/Status/IPCFault",        Value="true",    Type="Bool",   Unit="", Time= Google.Protobuf.WellKnownTypes.Timestamp.FromDateTime( DateTime.Now.ToUniversalTime())},
            };
            request.List.AddRange(list);
            await publisherClient.PublishAsync(request);
        }
        public async Task OpcPublishGrpcStreamTest()
        {
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
            AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2Support", true);
            var channel = GrpcChannel.ForAddress("http://localhost:19007");
            var publisherClient = new OpcPublisher.OpcPublisherClient(channel);
            var tokenSource = new CancellationTokenSource();
            var stream = publisherClient.ConnectForFeedback(new FeedbackKeyPrefix { Prefix = "ZS/ZS1" }).ResponseStream;
            while (await stream.MoveNext(tokenSource.Token))
            {
                var data = stream.Current;
                Console.WriteLine(data);
            }
        }
    }
}
